package com.yhy.dubbo.service.mongo;

import com.yhy.domain.mongo.Friend;
import com.yhy.domain.vo.PageResult;
import com.yhy.dubbo.api.mongo.FriendApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void addContacts(Long userId, Long friendUserId) {

        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendUserId));

        //判断mongodb好友关系表中这两个用户有没有关联
        if(!mongoTemplate.exists(query, Friend.class)){
            Friend friend1 = new Friend();
            friend1.setUserId(userId);
            friend1.setFriendId(friendUserId);
            friend1.setId(new ObjectId());
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }
        query = new Query(Criteria.where("userId").is(friendUserId).and("friendId").is(userId));

        if(!mongoTemplate.exists(query,Friend.class)){
            Friend friend2 = new Friend();
            friend2.setUserId(friendUserId);
            friend2.setFriendId(userId);
            friend2.setId(new ObjectId());
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }
    }

    @Override
    public PageResult findAllFriend(Integer page, Integer pagesize, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);

        long count = mongoTemplate.count(new Query(criteria), Friend.class);

        Query query = new Query(criteria)
                .skip((page-1)* pagesize)
                .limit(pagesize);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        return new PageResult(page,pagesize, (int) count,friends);
    }

    @Override
    public void delete(Long userId, Long likeUserId) {
        Criteria criteria1 = Criteria.where("userId").is(userId).and("friendId").is(likeUserId);
        mongoTemplate.remove(new Query(criteria1),Friend.class);

        Criteria criteria2 = Criteria.where("userId").is(likeUserId).and("friendId").is(userId);
        mongoTemplate.remove(new Query(criteria2),Friend.class);
    }
}
